<template>
  <view>
    <van-notice-bar left-icon="info-o" text="可填写手机号和固话（固话需加上区号）" />
    <view class="bg-white">
      <view v-for="(item, index) in state.phoneArr" :key="index" class="flex items-center">
        <view class="w-98%">
          <van-cell-group inset>
            <van-field :value="item.linkName" placeholder="请输入联系人姓名" :label="'联系人' + (index + 1)" clearable @change="item.linkName = $event.detail" />
            <van-field :value="item.linkPhone" placeholder="请输入联系电话" :border="false" label="联系电话" clearable @change="item.linkPhone = $event.detail" />
          </van-cell-group>
        </view>
      </view>
    </view>
    <view class="w-full fixed c-pd" :style="{ bottom: `${store.$state.systemInfo.safeAreaInsets!.bottom}px` }">
      <van-button type="primary" block @click="handleSubmit">保存</van-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import useModal from '@/hooks/useModal';
import EquipRequest from '@/request/equipRequest';
import { useAppStore } from '@/store';

interface IState {
  phoneArr: {
    linkName: string;
    linkPhone: string;
  }[];
  equipId: number;
  equipType: number;
}

interface IProps {
  equipId: number;
  equipType: number;
}

const { showModal } = useModal();

const store = useAppStore();

const props = defineProps<IProps>();

const state = reactive<IState>({
  phoneArr: [
    {
      linkName: '',
      linkPhone: '',
    },
    {
      linkName: '',
      linkPhone: '',
    },
    {
      linkName: '11',
      linkPhone: '',
    },
    {
      linkName: '',
      linkPhone: '',
    },
    {
      linkName: '',
      linkPhone: '',
    },
  ],
  equipId: 0,
  equipType: 1, //呼叫器2 其他类型1
});

onMounted(() => {
  state.equipId = props.equipId;
  state.equipType = props.equipType;
  getContact();
});

const getContact = () => {
  EquipRequest.GetContact({
    equipId: state.equipId,
    hasLoading: true,
  }).then((res) => {
    if (!res.data || !res.data.linkNames) return;
    let { linkNames, linkPhones } = res.data;
    if (linkNames) {
      let namesArray: string[] = linkNames.split(',');
      let phonesArray: string[] = linkPhones.split(',');
      for (let i = 0; i < state.phoneArr.length; i++) {
        state.phoneArr[i].linkName = namesArray[i] === '*' ? '' : namesArray[i];
        state.phoneArr[i].linkPhone = phonesArray[i] === '*' ? '' : phonesArray[i];
      }
    }
  });
};

const checkData = () => {
  const { phoneArr } = state;
  const phoneReg = /^\d+$/;
  const isValid = phoneArr.some((obj) => obj.linkName !== '' && obj.linkPhone !== '');
  if (isValid) {
    for (let index in phoneArr) {
      if (!phoneArr[index].linkName && phoneArr[index].linkPhone) {
        showModal(`第${Number(index) + 1}个电话号码的联系人姓名未填写`);
        return false;
      }
      if (!phoneArr[index].linkPhone && phoneArr[index].linkName) {
        showModal(`第${Number(index) + 1}个联系人的电话号码未填写`);
        return false;
      }
      // 检查电话号码格式
      if (phoneArr[index].linkPhone && !phoneReg.test(phoneArr[index].linkPhone)) {
        showModal(`第${Number(index) + 1}个电话号码格式错误`);
        return false;
      }
    }
    return true;
  } else {
    showModal('至少填写一个联系人姓名和电话');
    return false;
  }
};

const handleSubmit = () => {
  if (!checkData()) return;
  showModal('确定保存').then(() => {
    const { phoneArr, equipId } = state;
    const params: {
      equipId: number;
      fifthName?: string;
      fifthPhone?: string;
      firstName?: string;
      firstPhone?: string;
      fourthName?: string;
      fourthPhone?: string;
      secondName?: string;
      secondPhone?: string;
      thirdName?: string;
      thirdPhone?: string;
    } = {
      equipId,
    };
    phoneArr.forEach((item, index) => {
      params[`${index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : index === 3 ? 'fourth' : 'fifth'}Name`] = item.linkName;
      params[`${index === 0 ? 'first' : index === 1 ? 'second' : index === 2 ? 'third' : index === 3 ? 'fourth' : 'fifth'}Phone`] = item.linkPhone;
    });
    EquipRequest.SetBeeperContacts(params).then((res) => {
      if (res.status === 0) {
        showModal('设置成功');
        setTimeout(() => {
          getContact();
        }, 1000);
      } else {
        showModal(res.msg);
      }
    });
  });
};
</script>
